package ex401.util;

import ex401.shape.CircleComponent;
import ex401.shape.Component;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

public class Components {
    public static final String CONFIG_FILE = "/ex401/config/component.properties";

    public static Properties loadComponentType() {
        Properties properties = new Properties();
        try {
            InputStream inputStream = Components.class.getResourceAsStream(CONFIG_FILE);
            properties.load(inputStream);
        } catch (FileNotFoundException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
        return properties;
    }

    public static List<Component> loadComponents(Scanner scanner) {
        List<Component> list = new ArrayList<>();
        Properties properties = loadComponentType();
        String line = null;
        while ((line = scanner.nextLine()).length() > 0) {
            String[] args = line.split(" ");
            String[] classProperty = properties.getProperty(args[0]).split(",");
            String className = classProperty[0];
            int count = Integer.valueOf(classProperty[1]);
            Class<?>[] type = new Class[count + 1];
            Arrays.fill(type, Double.class);
            type[0] = Character.class;
            Object[] data = new Object[count + 1];
            data[0] = args[0].charAt(0);
            for (int i = 1; i < data.length; i++) {
                data[i] = Double.valueOf(args[i]);
            }
            Class cl = null;
            try {
                cl = Class.forName(className);
                Component c = (Component) (cl.getConstructor(type).newInstance(data));
                list.add(c);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
        return list;
    }

    public static double totalArea(List<Component> list) {
        double result = 0.0;
        for (Component c : list) {
            result += c.getArea();
        }
        return result;
    }
}
